package com.begye.smartloan.apptest.renzheng.bangka

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.begye.smartloan.apptest.MyApplication
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.SysConfigTool
import com.begye.smartloan.apptest.tool.doPostRequest
import org.json.JSONArray
import org.json.JSONObject

class RenZhengBangKaViewModel : ViewModel() {

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    private val _bangKaListLiveData = MutableLiveData<List<JSONObject>>()
    val onBangKaListLiveData get() = _bangKaListLiveData

    private val _needBangKaSameChannelLiveData = MutableLiveData<JSONObject?>()
    val onNeedBangKaSameChannelLiveData get() = _needBangKaSameChannelLiveData

    fun currentBangKaList(): List<JSONObject> {
        val obj = _bangKaListLiveData.value ?: return listOf()

        val newList = mutableListOf<JSONObject>()
        for (item in obj) {
            if (!item.optBoolean("isAdd", false)) {
                newList.add(JSONObject(item.toString()))
            }
        }
        return newList
    }

    fun hasNoBangKaItems(): Boolean {
        _bangKaListLiveData.value?.let { result ->
            val hasAdd = result.any {
                !it.optBoolean("isAdd", false)
            }
            if (hasAdd) {
                return false
            }
        }
        return true
    }

    fun hasLessThan2BangKaItems(): Boolean {
        _bangKaListLiveData.value?.let { result ->
            val isAdd = result.any {
                it.optBoolean("isAdd", false)
            }
            if (isAdd) {
                return false
            }
        }
        return true
    }

    /**
     * save page items
     */
    fun requestSaveBangKa(params: HashMap<String, Any>) {
        doPostRequest(
            path = "/sng7AoOELBzf3DMOLHFoHA",
            action = params,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    requestBangKaList()
                    val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                    val otherChannel = obj.optString("channel")
                    val needBingKaSameChannel = obj.optString("addBindFlag") == "YES"
                    if (needBingKaSameChannel and otherChannel.isNotBlank()) {
                        val result = SysConfigTool.filterBangKaChannel(otherChannel)
                        result?.let {
                            val walletMobile = jsonObject.optString("walletMobile", "")
                            it.put("walletMobile", walletMobile)
                            it.put("walletChannel", otherChannel)
                            it.put("walletDesc", it.optString("desc", ""))
                            it.put("walletLogo", it.optString("logo", ""))
                            _needBangKaSameChannelLiveData.value = it
                        }
                    } else {
                        _needBangKaSameChannelLiveData.value = null
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }
            })
    }

    /**
     * delete page items
     */
    fun requestDeleteBangKa(ids: String) {
        val params = hashMapOf<String, Any>().apply {
            put("ids", ids)
        }
        doPostRequest(
            path = "/kRtUi7szcRoL6YuZOJ5GA",
            action = params,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    requestBangKaList()
                }

                override fun onApiError(code: String, errMsg: String) {
                }
            })
    }

    /**
     * get wallet list
     */
    fun requestBangKaList() {
        doPostRequest(
            path = "/v0v2c30oj7QBZsF1V0PQqgQ",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    val obj = jsonObject.optJSONArray("obj") ?: JSONArray()
                    val list = mutableListOf<JSONObject>()
                    for (index in 0 until obj.length()) {
                        val item = obj.optJSONObject(index)
                        if (item != null) {
                            val listIndex = (index + 1).toString()
                            val title =
                                MyApplication.context.getString(R.string.fill_text_14, listIndex)
                            item.put("isAdd", false)
                            item.put("title", title)
                            list.add(item)
                        }
                    }
                    if (list.size < 2) {
                        val listIndex = (list.size + 1).toString()
                        val title =
                            MyApplication.context.getString(R.string.fill_text_14, listIndex)
                        list.add(JSONObject().apply {
                            put("isAdd", true)
                            put("title", title)
                        })
                    }
                    if (list.size < 2) {
                        val listIndex = (list.size + 1).toString()
                        val title =
                            MyApplication.context.getString(R.string.fill_text_14, listIndex)
                        list.add(JSONObject().apply {
                            put("isAdd", true)
                            put("title", title)
                        })
                    }
                    _bangKaListLiveData.value = list
                }

                override fun onApiError(code: String, errMsg: String) {
                }
            })
    }
}